#include "Command.h"
#include <sstream>

AddTaskCommand::AddTaskCommand(const std::string& description, 
                              Priority priority, const std::string& dueDate)
    : description(description), priority(priority), dueDate(dueDate) {}

std::string AddTaskCommand::executeImpl(TaskManager& manager) {
    int newId = manager.addTask(description, priority, dueDate);
    Logger::getInstance().log("添加任务: ID=" + std::to_string(newId));
    
    std::ostringstream oss;
    oss << "任务添加成功! ID: " << newId;
    return oss.str();
}

DeleteTaskCommand::DeleteTaskCommand(int id) : id(id) {}

std::string DeleteTaskCommand::executeImpl(TaskManager& manager) {
    bool success = manager.deleteTask(id);
    if (success) {
        Logger::getInstance().log("删除任务: ID=" + std::to_string(id));
        return "任务删除成功! ID: " + std::to_string(id);
    } else {
        return "错误: 找不到ID为 " + std::to_string(id) + " 的任务";
    }
}

ListTasksCommand::ListTasksCommand(const std::string& sortBy) : sortBy(sortBy) {}

std::string ListTasksCommand::executeImpl(TaskManager& manager) {
    Logger::getInstance().log("查看任务列表");
    
    auto tasks = manager.getAllTasks();
    
    // 排序
    if (sortBy == "priority") {
        std::sort(tasks.begin(), tasks.end(), [](const Task& a, const Task& b) {
            return a.getPriority() > b.getPriority(); // 高优先级在前
        });
    } else if (sortBy == "date") {
        std::sort(tasks.begin(), tasks.end(), [](const Task& a, const Task& b) {
            return a.getDueDate() < b.getDueDate(); // 早的日期在前
        });
    }
    
    if (tasks.empty()) {
        return "当前没有任务";
    }
    
    std::ostringstream oss;
    oss << "任务列表 (" << tasks.size() << " 个任务):\n";
    for (const auto& task : tasks) {
        oss << task.toString() << "\n";
    }
    return oss.str();
}

UpdateTaskCommand::UpdateTaskCommand(int id, const std::string& description, 
                                   std::optional<Priority> priority, const std::string& dueDate)
    : id(id), description(description), priority(priority), dueDate(dueDate) {}

std::string UpdateTaskCommand::executeImpl(TaskManager& manager) {
    bool updated = false;
    
    // 更新描述
    if (!description.empty()) {
        manager.updateTaskDescription(id, description);
        updated = true;
    }
    
    // 更新优先级
    if (priority.has_value()) {
        manager.updateTaskPriority(id, priority.value());
        updated = true;
    }
    
    // 更新截止日期
    if (!dueDate.empty()) {
        manager.updateTaskDueDate(id, dueDate);
        updated = true;
    }
    
    if (updated) {
        Logger::getInstance().log("更新任务: ID=" + std::to_string(id));
        return "任务更新成功! ID: " + std::to_string(id);
    } else {
        return "错误: 没有提供更新内容或找不到ID为 " + std::to_string(id) + " 的任务";
    }
}